package edu.zut.software.identity.controller;

import edu.zut.software.identity.Service.impl.StuCollegeServiceImpl;
import edu.zut.software.identity.Service.impl.StuGradeServiceImpl;
import edu.zut.software.identity.Service.impl.StuMajorServiceImpl;
import edu.zut.software.identity.constant.WorkWXAPI;
import edu.zut.software.identity.domain.StuCollege;
import edu.zut.software.identity.domain.StuGrade;
import edu.zut.software.identity.domain.StuMajor;
import edu.zut.software.identity.domain.Student;
import edu.zut.software.identity.utils.HttpClientUtil;

import edu.zut.software.identity.utils.WXAPIUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.Id;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/college")
public class CollegeController {
    private static final Logger logger = LoggerFactory.getLogger(CollegeController.class);


    public StuCollegeServiceImpl collegeService;
    @Autowired
    public void setCollegeService(StuCollegeServiceImpl collegeService) {
        this.collegeService = collegeService;
    }

    public StuMajorServiceImpl majorService;
    @Autowired
    public void setMajorService(StuMajorServiceImpl majorService) {
        this.majorService = majorService;
    }

    public StuGradeServiceImpl gradeService;
    @Autowired
    public void setGradeService(StuGradeServiceImpl gradeService) {
        this.gradeService = gradeService;
    }

    @GetMapping("/findById/{id}")
    public StuCollege findById(@PathVariable("id") String id) {
        return collegeService.findById(id);
    }

    @RequestMapping("/f2")
    public List<StuCollege> findAll() {
        List<StuCollege> all = collegeService.findAll();
        for (StuCollege stuCollege : all) {
            System.out.println(stuCollege);
        }
        return all;
    }
    @PutMapping("/updateCollege")
    public String updateCollege(@RequestBody StuCollege stuCollege){
        collegeService.save(stuCollege);
        return "success";
    }


    /**
     * 创建学院部门
     */
    public void createCollegeDepartment(StuCollege stuCollegeInfo) {

        Map<String, Object> jsonMap= WXAPIUtil.createDepartment(stuCollegeInfo.getName(), stuCollegeInfo.getWx_parentid(), stuCollegeInfo.getPx());
        if(Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
            stuCollegeInfo.setWx_id(Integer.parseInt(jsonMap.get("id").toString()));
            collegeService.save(stuCollegeInfo);
            logger.info("创建学院部门:{},状态:{}", stuCollegeInfo.getName() , "成功！");
        }
        else {
            logger.info("创建学院部门:{},状态:{}", stuCollegeInfo.getName() , "失败！");

        }
    }

    /**
     * 创建专业部门
     */
    public void createMajorDepartment(StuMajor stuMajorInfo){
       int majorParentId=collegeService.findById(stuMajorInfo.getCollege_id()).getWx_id();
        Map<String, Object> jsonMap= WXAPIUtil.createDepartment(stuMajorInfo.getName(),majorParentId, stuMajorInfo.getPx());
        if(Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
            stuMajorInfo.setWx_id(Integer.parseInt(jsonMap.get("id").toString()));
            majorService.save(stuMajorInfo);
            logger.info("创建专业部门:{},状态:{}", stuMajorInfo.getName() , "成功！");
        }
        else {
            logger.info("创建专业部门:{},状态:{}", stuMajorInfo.getName() , "失败！");
        }
    }

    /**
     * 创建年级部门
     * @param stuGradeInfo
     */
    public  void createGradeDepartment(StuGrade stuGradeInfo){
        int gradeParentId=majorService.findById(stuGradeInfo.getMajorId()).getWx_id();
        Map<String, Object> jsonMap= WXAPIUtil.createDepartment(stuGradeInfo.getName(),gradeParentId, stuGradeInfo.getPx());
        if(Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
            stuGradeInfo.setWx_id(Integer.parseInt(jsonMap.get("id").toString()));
            gradeService.save(stuGradeInfo);
            logger.info("创建年级部门:{},状态:{}", stuGradeInfo.getName() , "成功！");
        }
        else {
            logger.info("创建年级部门:{},状态:{}", stuGradeInfo.getName() , "失败！");
        }
    }

    @RequestMapping("/createDepartment")
    public String updateStu(){
        String data = "";
        Map<String, Object> returnMap = new HashMap<>();
        List<StuCollege> stuCollegeList = collegeService.findAll();
        boolean collegeSet = true,majorSet=true,gradeSet=true;
        for (StuCollege stuCollegeInfo : stuCollegeList) {
            if (stuCollegeInfo.getWx_id() == 0) {  //wx_id为空，创建学院
                createCollegeDepartment(stuCollegeInfo);
                data += stuCollegeInfo.toString();
                collegeSet=false;
            }
        }
        if (collegeSet){
            logger.info("学院已经全部创建");
        }
                List<StuMajor> stuMajorList =majorService.findAll();
                for (StuMajor stuMajorInfo : stuMajorList){
                    if (stuMajorInfo.getWx_id()==0){         //wxId为空，创建专业
                        createMajorDepartment(stuMajorInfo);
                        majorSet=false;
                    }
                }
        if (majorSet){
            logger.info("专业已经全部创建");
        }
        List<StuGrade> stuGradeList =gradeService.findAll();
        for (StuGrade stuGradeInfo : stuGradeList){
            if (stuGradeInfo.getWx_id() ==0){
                createGradeDepartment(stuGradeInfo);
               gradeSet=false;
            }
        }
        if (gradeSet){
            logger.info("年级已经全部创建");
        }
        return data;
    }

    /**
     *
     * @param modelAndView
     * @return
     */
    @GetMapping("/")
    public ModelAndView index(ModelAndView modelAndView){
        modelAndView.setViewName("stu/depart_info");
        return modelAndView;
    }

    @PostMapping("/search/{page}/{number}")
  //  @ResponseBody
    public Page<StuCollege> search(@PathVariable Integer page, @PathVariable Integer number, @RequestParam String name) {
        if(number == null && number.equals(0)){
            number = 15;
        }
        return collegeService.findAll(page-1, number, name);
    }

    @GetMapping("/search/{page}/{number}")
    //  @ResponseBody
    public Page<StuCollege> search(@PathVariable Integer page, @PathVariable Integer number) {
        if(number == null && number.equals(0)){
            number = 15;
        }
        return collegeService.findAll(page-1, number);
    }

    @PostMapping("/saveCollege")
    public String saveCollege(@RequestBody StuCollege stuCollege){
        stuCollege.setWx_parentid(2);          //2为本专科生wx_id
        collegeService.save(stuCollege);
        return "success";
    }
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") String id){
        collegeService.deleteById(id);
    }

    /**
     * 以下为专业Major的的方法
     * */

    @GetMapping("/searchMajor/{page}/{number}")
    //  @ResponseBody
    public Page<StuMajor> searchMajor(@PathVariable Integer page, @PathVariable Integer number) {
        return majorService.findAll(page-1, number);
    }
    @PostMapping("/saveMajor")
    public String saveMajor(@RequestBody StuMajor stuMajor){
        System.out.println(stuMajor);
        majorService.save(stuMajor);
        return "success";
    }
    @DeleteMapping("/deleteMajorById/{id}")
    public void deleteMajorById(@PathVariable("id") String id){
        majorService.deleteById(id);
    }
    @GetMapping("/findMajorById/{id}")
    public StuMajor findMajorById(@PathVariable("id") String id) {
        return majorService.findById(id);
    }

    @GetMapping("/getMajorInfoByCollegeId/{Id}")
    public  List<StuMajor> getMajorInfoByCollegeId(@PathVariable String Id){
        return majorService.getMajorInfoByCollegeId(Id);
    }

    /**以下为年级Grade的的方法*/

    @GetMapping("/searchGrade/{page}/{number}")
    //  @ResponseBody
    public Page<StuGrade> searchGrade(@PathVariable Integer page, @PathVariable Integer number) {
        return gradeService.findAll(page-1, number);
    }
    @PostMapping("/saveGrade")
    public String saveGrade(@RequestBody StuGrade stuGrade){
        gradeService.save(stuGrade);
        return "success";
    }
    @DeleteMapping("/deleteGradeById/{id}")
    public void deleteGradeById(@PathVariable("id") String id){
        gradeService.deleteById(id);
    }
    @GetMapping("/findGradeById/{id}")
    public StuGrade findGradeById(@PathVariable("id") String id) {
        return gradeService.findById(id);
    }

    @GetMapping("/getGradeInfoByMajorId/{Id}")
    public  List<StuGrade> getGradeInfoByMajorId(@PathVariable String Id){
        return gradeService.getGradeInfoByMajorId(Id);
    }

    public static boolean stopFlag =false;
    @RequestMapping("ange/{id}")
    public String test(@PathVariable("id") String id) {
        boolean flag=true;
        boolean one=false;

        if(id.equals("1"))
            CollegeController.stopFlag = flag;
        if(id.equals("2"))
            CollegeController.stopFlag = one;

        return "ok";
    }



    @RequestMapping("/listDepartment")
    public Object listDepartment(){
        Map<String,Object>returnmap;
        return HttpClientUtil.wxRequest(GetAccessToken.getAccessToken(), String.format(WorkWXAPI.DEPARTMENT_LIST,
                GetAccessToken.getAccessToken()), null, HttpClientUtil.METHOD_GET).get("department");
    }
    @RequestMapping("/deleteDepartment/{p1}")
    public String deleDepartment(@PathVariable String p1){
        Map<String,Object> returnMap=WXAPIUtil.deleteDepartment(p1);
        if (Integer.parseInt(returnMap.get("errcode").toString())==0){
            collegeService.deleteById(p1);
            return "删除"+"成功";
        }
        return "删除失败(不能删除根部门；不能删除含有子部门、成员的部门)";
    }

}